package penguin.transfer.netty.client;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.timeout.IdleStateAwareChannelHandler;
import org.jboss.netty.handler.timeout.IdleStateEvent;
import org.jboss.netty.handler.timeout.ReadTimeoutException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import penguin.transfer.dto.TransferDTO;

/**
 *  * socket 空闲 处理 类
 * 当读空闲足够时间的时候会调用此方法抛出超时异常
 * 当读空闲足够时间的时候会调用此方法抛出超时异常
 * 用于客户端
 * <br/> Created on 15/1/12 上午10:27
 *
 * @author 王建华(penguin83@126.com)
 */
public class NettyClientIdleStateAwareChannelHandler extends IdleStateAwareChannelHandler  {

    @Override
    public void channelIdle(ChannelHandlerContext ctx,IdleStateEvent e) throws Exception{

        super.channelIdle(ctx,e);
        Channel channel=e.getChannel();
        switch(e.getState()){
            case WRITER_IDLE: {
                if(channel != null && channel.isWritable()) {
                    TransferDTO transferDTO = TransferDTO.buildHeart();
                    channel.write(transferDTO);
                }
                else{
                    throw new ReadTimeoutException("channel无法写消息，心跳消息无法发送"+e.getChannel().getId());
                }
                break;
            }
            case READER_IDLE: {
                throw new ReadTimeoutException("读空闲超时，抛出超时异常。"+e.getChannel().getId());
            }

        }

    }

}
